import 'dart:math';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
// import 'package:image_gallery_saver/image_gallery_saver.dart';

import 'package:permission_handler/permission_handler.dart';
import 'package:qr_flutter/qr_flutter.dart';

import 'dart:ui' as ui;

import 'package:scanQrCode/utils/Toast.dart';

class QrcodePage extends StatefulWidget {
  QrcodePage({Key key, this.body}) : super(key: key);
  String body = '';

  @override
  _QrcodePage createState() => _QrcodePage();
}

class _QrcodePage extends State<QrcodePage> {
  GlobalKey _globalKey = new GlobalKey();
  int colorNow = 0;

  random() {
    var rng = new Random(); //随机数生成类
    setState(() {
      colorNow = rng.nextInt(10);
    });
  }

  List colorArr = [
    Colors.greenAccent,
    Colors.orangeAccent,
    Colors.tealAccent,
    Colors.redAccent,
    Colors.blueAccent,
    Colors.yellowAccent[600],
    Colors.pinkAccent,
    Colors.purpleAccent,
    Colors.amberAccent,
    Colors.cyanAccent,
  ];

  @override
  void initState() {
    random();
    var permission =
        PermissionHandler().checkPermissionStatus(PermissionGroup.storage);
    print("permission status is " + permission.toString());
    PermissionHandler().requestPermissions(<PermissionGroup>[
      PermissionGroup.storage, // 在这里添加需要的权限
    ]);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          leading: BackButton(color: Colors.white),
          title: Text('生成二维码',
              style: TextStyle(
                color: Colors.white, //设置字体颜色
                fontSize: 20, //设置字体大小
              )),
        ),
        body: Column(
          children: [
            SizedBox(
              height: 90,
            ),
            Container(
              child: Center(
                  child: RepaintBoundary(
                      key: _globalKey,
                      child: QrImage(
                          data: widget.body,
                          size: 300.0,
                          foregroundColor: colorArr[colorNow],
                          errorStateBuilder: (cxt, err) {
                            return Container(
                              child: Center(
                                child: Text(
                                  "抱歉~，您生成的二维码走丢了，请重试",
                                  textAlign: TextAlign.center,
                                ),
                              ),
                            );
                          }))),
            ),
            SizedBox(
              height: 30,
            ),
            RaisedButton(
              color: Colors.orangeAccent,
              child: new Text('保存图片',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16, //设置字体大小
                  )),
              onPressed: () async {
                BuildContext buildContext = _globalKey.currentContext;
                if (null != buildContext) {
                  RenderRepaintBoundary boundary =
                      buildContext.findRenderObject();
                  ui.Image image = await boundary.toImage();
                  ByteData byteData =
                      await image.toByteData(format: ui.ImageByteFormat.png);
                  final result = await ImageGallerySaver.saveImage(
                      byteData.buffer.asUint8List());
                  print(byteData.buffer.asUint8List());

                  if (result != null) {
                    Toast.toast(context, msg: '已保存到相册');
                  } else {
                    Toast.toast(context, msg: '保存失败');
                  }
                }
              },
            )
          ],
        ));
  }
}
